package com.czxy.changgou3.controller;

import com.czxy.changgou3.cart.Cart;
import com.czxy.changgou3.config.JwtProperties;
import com.czxy.changgou3.pojo.User;
import com.czxy.changgou3.service.CartService;
import com.czxy.changgou3.vo.CartVo;
import com.czxy.utils.JwtUtils;
import com.czxy.vo.BaseResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/5/3
 */
@RestController
@RequestMapping("/carts")
public class CartController {

    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private HttpServletRequest request;
    @Resource
    private CartService cartService;

    @PostMapping
    public BaseResult addOrder(@RequestBody CartVo cartVo){
        //1 校验用户
        User loginUser = null;
        try {
            String token = request.getHeader("Authorization");
            System.out.println(token);
            loginUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), User.class);
        } catch (Exception e) {
            return BaseResult.error("token无效");
        }

        //2 添加购物车
        cartService.addCart(loginUser, cartVo);

        //3 提示
        return BaseResult.ok("添加成功");
    }

    @GetMapping
    public BaseResult queryCartList(){
        //1 校验用户
        User loginUser = null;
        try {
            String token = request.getHeader("Authorization");
            loginUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), User.class);
        } catch (Exception e) {
            return BaseResult.error("token无效");
        }

        //2 查询购物车
        Cart cart = cartService.queryCartList(loginUser);

        //3 提示
        return BaseResult.ok("查询成功", cart.getData().values() );
    }

    @PutMapping
    public BaseResult updateCart(@RequestBody List<CartVo> cartVoList){
        try {
            //1 用户
            User loginUser = null;
            try {
                String token = request.getHeader("Authorization");
                loginUser = JwtUtils.getObjectFromToken(token, jwtProperties.getPublicKey(), User.class);
            } catch (Exception e) {
                return BaseResult.error("token无效");
            }

            //2 更新
            cartService.updateCart(loginUser ,cartVoList );

            //3 提示
            return BaseResult.ok("更新成功");
        } catch (Exception e) {
            //错误提示
            return BaseResult.error(e.getMessage());
        }

    }
}
